import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

class MyWebViewPage extends StatefulWidget {
  final String title;
  final Map<String, dynamic>? userProfileData;

  const MyWebViewPage({
    super.key,
    required this.title,
    this.userProfileData,
  });

  @override
  State<MyWebViewPage> createState() => _MyWebViewPageState();
}

class _MyWebViewPageState extends State<MyWebViewPage> {
  InAppWebViewController? webViewController;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.title)),
      body: Column(
        children: [
          Expanded(
            child: InAppWebView(
              initialUrlRequest: URLRequest(
                url: WebUri("http://192.168.31.152:5500/test.html"),
              ),
              onWebViewCreated: (controller) {
                webViewController = controller;

                // Flutter监听JS消息
                controller.addJavaScriptHandler(
                  handlerName: 'sendToFlutter',
                  callback: (args) {
                    String message = args.isNotEmpty ? args[0] : "空消息";
                    _showDialogFromWeb(message);
                    return {'status': 'ok', 'echo': message}; // 返回值
                  },
                );
              },
              onLoadStop: (controller, url) {
                final data = widget.userProfileData ?? {};
                final jsonStr = jsonEncode(data); // Map → JSON 字符串
                controller.evaluateJavascript(
                  source: "setMessageFromFlutter($jsonStr);", // 直接传 JSON
                );
              },
            ),
          ),
          ElevatedButton(
            child: const Text("发消息给网页"),
            onPressed: () {
              webViewController?.evaluateJavascript(
                source: "setMessageFromFlutter('${123123}');",
              );
            },
          )
        ],
      ),
    );
  }

  void _showDialogFromWeb(String msg) {
    showDialog(
      context: context,
      builder: (_) => AlertDialog(
        title: const Text("来自网页的消息"),
        content: Text(msg),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text("关闭"),
          )
        ],
      ),
    );
  }
}
